from django.db import models
from django.contrib.auth import get_user_model
from ckeditor_uploader.fields import RichTextUploadingField
from django.utils.timezone import timedelta
User = get_user_model()


# Create your models here.

class MovieStaffCategory(models.Model):
    """
    电影职员类型(1导演、2演员、3编剧、4制片人等)
    """
    add_time = models.DateTimeField(auto_now=True, verbose_name='添加时间', help_text='添加时间')
    name = models.CharField(max_length=20, unique=True, verbose_name='职业名称', help_text='职业名称')
    desc = models.CharField(max_length=100, blank=True, verbose_name='说明', help_text='说明')

    class Meta:
        verbose_name = '电影职员类型(导演,演员)'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class MovieCountry(models.Model):
    """
    电影所属国家
    """
    name = models.CharField(max_length=20, verbose_name='电影所属国家', help_text='电影所属国家')
    add_time = models.DateTimeField(auto_now=True, verbose_name='添加时间', help_text='添加时间')

    class Meta:
        verbose_name = '电影所属国家'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class MovieTypeCategory(models.Model):
    """
    电影制式分类(2D,3D,IMAX)
    """
    name = models.CharField(max_length=10, unique=True, verbose_name='电影的类型', help_text='电影的类型')
    desc = models.CharField(max_length=100, blank=True, verbose_name='简介这个类型', help_text='简介这个类型')
    add_time = models.DateTimeField(auto_now=True, verbose_name='添加时间', help_text='添加时间')

    class Meta:
        verbose_name = '电影制作类型'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class MovieKindCategory(models.Model):
    """
    电影归类(动作,悬疑,科幻)
    """
    name = models.CharField(max_length=10, unique=True, verbose_name='电影归类(动作,悬疑,科幻)', help_text='电影归类(动作,悬疑,科幻)')
    desc = models.CharField(max_length=100, blank=True, verbose_name='简介这个类型', help_text='简介这个类型', default="")
    add_time = models.DateTimeField(auto_now=True, verbose_name='添加时间', help_text='添加时间')

    class Meta:
        verbose_name = '电影归类(动作,悬疑,科幻)'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class MovieStaff(models.Model):
    """
    电影职员详细信息
    """
    name = models.CharField(verbose_name='演员名称', max_length=50, unique=True, help_text='演员名称')
    desc = models.TextField(max_length=500, verbose_name='简介', blank=True, help_text=True)
    type = models.ManyToManyField(MovieStaffCategory, verbose_name='职业', help_text='职业')
    add_time = models.DateTimeField(auto_now=True, verbose_name='添加时间', help_text='添加时间')

    class Meta:
        verbose_name = '电影职员详细信息'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


import uuid
from django.utils.timezone import now


def directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
    filename_arr = filename.split('.')
    ext = filename_arr[-1]
    string = uuid.uuid4().hex
    file_name = string + '.' + ext
    year = now().year
    month = now().month
    return 'img/{}/{}/{}'.format(year, month, file_name)


from django.utils.deconstruct import deconstructible
import os


@deconstructible
class UploadToPathAndRename(object):
    def __init__(self, path):
        year = str(now().year)
        month = str(now().month)

        self.sub_path = os.path.join(path, year, month)

    def __call__(self, instance, filename):
        ext = filename.split('.')[-1]
        filename = '{}.{}'.format(uuid.uuid4().hex, ext)
        return os.path.join(self.sub_path, filename)


class MovieDetail(models.Model):
    """
    电影详细信息
    """
    STATUS = (
        (1, '已上映'),
        (2, '未上映'),
        (3, '已下架'),
    )
    IS_BANNER = (
        (True, '在首页轮播'),
        (False, "不轮播")
    )

    name = models.CharField(max_length=50, verbose_name='电影名字', help_text='请输入电影的名字')
    add_time = models.DateTimeField(verbose_name='信息添加时间', help_text='信息添加时间', auto_now=True)
    is_hot = models.BooleanField(default=False, verbose_name='正在热映', help_text='正在热映的电影')
    hot_index = models.CharField(max_length=3, default='0', verbose_name='热门中的排序', help_text='热门中的排序')
    coming_soon = models.BooleanField(default=False, verbose_name='即将上映的电影', help_text='即将上映的电影')
    coming_soon_index = models.CharField(max_length=3, default='0', verbose_name='即将上映的电影的排序', help_text='即将上映的电影的排序')
    on_sale_time = models.DateTimeField(auto_now=True, verbose_name='上映时间', help_text='上映时间')
    movie_brief = RichTextUploadingField(default='目前没有还有简介', max_length=3000, verbose_name='剧情简介', help_text='剧情简介')
    kind_category = models.ManyToManyField(MovieKindCategory, verbose_name='电影归类', help_text='电影归类')
    type_category = models.ManyToManyField(MovieTypeCategory, verbose_name='电影制作类型')
    status = models.IntegerField(default=2, verbose_name='上映状态', choices=STATUS, help_text='上映状态')
    banner_index = models.CharField(max_length=5, default='0', verbose_name='是否在选片的时候轮播的排序', help_text='是否在选片的时候轮播的排序')
    is_banner = models.BooleanField(default=False, choices=IS_BANNER, verbose_name='是否在展示的时候轮播',
                                    help_text='是否在展示的时候轮播')
    movie_length = models.CharField(max_length=5, default='120', verbose_name='影片时长,单位分钟')
    movie_state = models.ManyToManyField(MovieCountry, blank=True, verbose_name='电影所属国家', help_text='电影所属国家')
    # sub_title = models.ManyToManyField(SubTitle, verbose_name='电影副标题', help_text='电影副标题', blank=True, default="")

    staffs = models.ManyToManyField(MovieStaff, through='MovieAllStaffs', verbose_name='制作人员')
    view_num = models.PositiveIntegerField(default=0, verbose_name='用户浏览数量', help_text='用户浏览数量')
    # user_want_num = models.ManyToManyField(User, blank=True,null=True, default=None, verbose_name='用户想看', help_text='用户想看',
    #                                        related_name='want_user')

    # user_want_num = models.PositiveIntegerField()
    index_pic = models.ImageField(upload_to=UploadToPathAndRename("test_img"), null=True, default=None, blank=True)

    class Meta:
        verbose_name = '电影信息'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class MoviePics(models.Model):
    img = models.ImageField(upload_to='img')
    movie = models.ForeignKey(MovieDetail)
    add_time = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = '电影图集'
        verbose_name_plural = verbose_name


class MovieAllStaffs(models.Model):
    """
    如马特达蒙本人是导演 编剧 演员
    但是他在谍影重重中 是演员 并不是导演,所以我们需要给在本部电影中给定他的角色
    """
    staff = models.ForeignKey(MovieStaff, verbose_name='职员信息', help_text='职员信息')
    movie = models.ForeignKey(MovieDetail, verbose_name='所属电影', help_text='所属电影', related_name='staffs_in_movie')
    type = models.ForeignKey(MovieStaffCategory, verbose_name='所属类型', help_text='所属类型')

    class Meta:
        verbose_name = '每个电影职员信息'
        verbose_name_plural = verbose_name

        unique_together = ("staff", "movie", "type")


class Cinema(models.Model):
    name = models.CharField(max_length=30, verbose_name='影院名称')
    address = models.CharField(max_length=100, verbose_name='影院的地址')

    class Meta:
        verbose_name = '影院'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class MovieHall(models.Model):
    name = models.CharField(max_length=20, verbose_name='影厅')
    cinema = models.ForeignKey(Cinema, verbose_name='影厅所属的影院')

    class Meta:
        verbose_name = '影厅'
        verbose_name_plural = verbose_name

        unique_together = (
            "cinema",
            'name'
        )


    def __str__(self):
        return "{},{}厅".format(self.cinema.name,self.name)



class FilmSchedule(models.Model):
    """
    电影的片场
    """
    movie_hall = models.ForeignKey(MovieHall,verbose_name='片场所在的影厅')
    movie = models.ForeignKey(MovieDetail,verbose_name='片场播放的电影')
    price = models.FloatField(verbose_name='购票价格')
    kind = models.ForeignKey(MovieTypeCategory,verbose_name='3D/2D的播放格式')

    start_time = models.DateTimeField(verbose_name='电影开始时间',default=now)
    end_time = models.DateTimeField(verbose_name='电影结束时间',default=now)


    class Meta:
        verbose_name = '电影的片场'
        verbose_name_plural = '电影的片场'

    def __str__(self):
        return "电影{},影厅{},开始时间{},结束时间{}".format(self.movie.name,self.movie_hall.name,self.start_time,self.end_time)

    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):

        start_time = self.start_time
        movie_length = int(self.movie.movie_length)
        self.end_time = start_time + timedelta(minutes=movie_length)

        return super().save(force_insert=force_insert, force_update=force_update, using=None, update_fields=None)


class MovieHallSeat(models.Model):

    """
    实体的座位，表达了实际里面的真实的物理的座位
    """
    row = models.CharField(max_length=2,verbose_name='1,2,3 行')
    col = models.CharField(max_length=2,verbose_name='A,B,C 列')
    movie_hall = models.ForeignKey(MovieHall)

    class Meta:
        verbose_name = '实际物理座位它属于影厅'
        verbose_name_plural = verbose_name

    def __str__(self):
        return "{} 厅 {}行 {}列".format(self.movie_hall.name,self.row,self.col)



class TicketSeat(models.Model):
    """
    表示的是商品,电影票里面的座位信息
    """
    STATUS = (
        ('1','座位可选'),
        ('2','座位已经被够买'),
        ('3','锁定中,其他人正在付款')

    )
    movie_hall_seat = models.ForeignKey(MovieHallSeat,verbose_name='电影票里面的座位信息')
    film_schedule = models.ForeignKey(FilmSchedule,verbose_name='电影座位所属的片场',related_name="ticket_seat_film")
    status = models.CharField(max_length=2,choices=STATUS,verbose_name='座位状态',default='1')
    lock_time = models.DateTimeField(default=now,verbose_name='座位的锁定有效时间,当前时间大于锁定时间才能去够买')
    owner = models.ForeignKey(User,verbose_name='够买用户',null=True,default=None,blank=True)

    class Meta:
        verbose_name = '电影票里面的座位 他必须和物理座位有关联'
        verbose_name_plural = verbose_name

        unique_together = (
            'movie_hall_seat','film_schedule'
        )




"""
# 1.毛
#     影厅有座位,默认让他生成的时候就有座位 ---每次添加片场信息的时候,自动的根据这个影厅里面有多少来自动的填充
#     
# 2.赵
#     影厅座位量固定,每次够买票的时候,自增一个计数，计数到最大值,就不能够买票了
"""

"""
pre_save
post_save


pre_update
post_update

"""

